package org.jeecgframework.jwt.aop;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.jwt.def.JwtConstants;
import org.jeecgframework.jwt.model.TokenModel;
import org.jeecgframework.jwt.service.RedisTokenManager;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;

/**
 * 用于O2O多商家点餐接口 旧版为RestAuthTokenInterceptor 改用sing签名方式验证rest
 * api接口是否有权限访问，去掉繁杂的验证功能
 * 
 * @author 78292
 *
 */
@Component
public class RestAuthTokenForO2OInterceptor extends RestAuthTokenInterceptor {
	private static final String SIGN_KEY = "26F72780372E84B6CFAED6F7B19139CC47B1912B6CAED753";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		String requestPath = request.getRequestURI().substring(request.getContextPath().length());
		if (requestPath.indexOf("/rest/") == -1 || excludeUrls.contains(requestPath)
				|| moHuContain(excludeContainUrls, requestPath)) {
			return true;
		}
		if (requestPath.indexOf("/appapi/") == 5) {
			return true;
		}

		JSONObject j = new JSONObject();
		try {
			String sign = request.getHeader("X-SIGN");
			String token = request.getHeader("token");
			if (StringUtil.isEmpty(sign)) {
				throw new BusinessException("sign不能为空");
			}
			if (!sign.equals(SIGN_KEY)) {
				throw new BusinessException("签名验证失败");
			}
			// 登录请求则通过
			if (requestPath.contains("/login")) {
				return true;
			}
			if (StringUtil.isEmpty(token)) {
				throw new BusinessException("token不能为空");
			}
			RedisTokenManager RedisTokenManager = new RedisTokenManager();
			RedisTokenManager.getToken(token, "");
			// Map<String, String> paramMap =new HashMap<String, String>();
			// paramMap.put("body",body);
			// if(!SignatureUtil.checkSign(paramMap, SIGN_KEY, sign)){

		} catch (BusinessException e) {
			j.put("success", "false");
			j.put("msg", e.getMessage());
			response.getWriter().print(j.toJSONString());
			return false;

		}

		// 从header中得到token
		String authHeader = request.getHeader(JwtConstants.AUTHORIZATION);
		if (authHeader == null) {
			throw new ServletException("Missing or invalid X-AUTH-TOKEN header.");
		}
		// 验证token
		Claims claims = null;
		try {
			claims = Jwts.parser().setSigningKey(JwtConstants.JWT_SECRET).parseClaimsJws(authHeader).getBody();
		} catch (final SignatureException e) {
			throw new ServletException("Invalid token.");
		}

		Object username = claims.getId();
		if (oConvertUtils.isEmpty(username)) {
			throw new ServletException("Invalid X-AUTH-TOKEN Subject no exist username.");
		}
		TokenModel model = manager.getToken(authHeader, username.toString());
		/** 多请求，暂时关闭，会出现验证不通过 **/
		// if (manager.checkToken(model)) {
		// 如果token验证成功，将对象传递给下一个请求
		request.setAttribute(JwtConstants.CURRENT_TOKEN_CLAIMS, claims);
		// 如果token验证成功，将token对应的用户id存在request中，便于之后注入
		request.setAttribute(JwtConstants.CURRENT_USER_NAME, model.getUsername());
		return true;
		// } else {
		// 如果验证token失败，则返回401错误
		// response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		// return false;
		// }
	}

}
